
<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false" style="width: 35%;">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="100px">
      <el-form-item label="展会名称" prop="tid">
        <el-select placeholder="请选择展会名称" v-model="dataForm.tid" :disabled="dataForm.id" @change="getUrl2" clearable>
          <el-option v-for="option in templates" :key="option.id" :label="option.template"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分组">
        <el-select placeholder="请选择分组" v-model="dataForm.gid" clearable>
          <el-option v-for="option in groupList" :key="option.id" :label="option.groupName"
            :value="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="ly">
        <el-input v-model.trim="dataForm.ly" placeholder="来源为字母与数字组合" :disabled="dataForm.id" @change="getUrl"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
       <el-input v-model.trim="dataForm.remark" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="预登记" prop="isVip">
        <el-select v-model="dataForm.isVip" placeholder="请选择" clearable>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="链接地址" prop="url">
        <el-input v-model="dataForm.url" placeholder="请输入" disabled></el-input>
      </el-form-item>
      <!-- <el-form-item label="短链接" style="display:flex; justify-content: space-between; align-items: center;">
        <el-input v-model="dataForm.shortUrl" placeholder="点击按钮生成短链接" disabled
          style="width: 400px;margin-right: 20px;"></el-input>
        <el-button type="primary">生成短链接</el-button>
      </el-form-item> -->
      <el-form-item label="邮箱">
        <el-input v-model="dataForm.email" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-input v-model="dataForm.startTime" placeholder="YYYY-MM-DD hh:mm:ss"></el-input>
      </el-form-item>
      <el-form-item label="到期时间" prop="">
        <el-input v-model="dataForm.endTime" placeholder="YYYY-MM-DD hh:mm:ss" disabled></el-input>
      </el-form-item>
      <el-form-item label="人员授权">
        <el-select v-model="dataForm.userIds" :options="userList" placeholder="请选择人员授权"  multiple filterable>
          <el-option v-for="item in userList" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <div style="text-align: center;">
        <el-button  type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
        <el-button @click="close()">{{ $t("cancel") }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: null as any,
  tid: '', //展会名称
  gid: '', //分组
  ly: '', //来源
  remark: "",//备注
  isVip: "",//预登记
  shortUrl: null as any,//短连接
  url: '',//链接地址
  email: '',//邮箱
  startTime: '',//开始时间
  endTime: '',//到期时间
  daterange: null as any,
  userIds: [] as any,
  txIdentifySecretId: "",
  txIdentifrsecretKey: "",

});

const close = () => {
  visible.value = false;
  visible.value = false;
  dataForm.id = null;
  dataForm.tid = '';
  dataForm.gid = '';
  dataForm.ly = '';
  dataForm.remark = '';
  dataForm.isVip = '';
  dataForm.shortUrl = null;
  dataForm.url = '';
  dataForm.email = '';
  dataForm.startTime = '';
  dataForm.endTime = '';
  dataForm.daterange = null;
  dataForm.userIds = [];
  dataForm.txIdentifySecretId = '';
  dataForm.txIdentifrsecretKey = ''

}


//人员列表
const userList = ref<any[]>([]);


//校验
const rules = ref({
  remark: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  url: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  ly: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  tid: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  isVip: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  endTime: [{ required: true, message: t("validate.required"), trigger: "blur" }],

});

const init = async (id?: number) => {
  visible.value = true;
  dataForm.id = id;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  const promises = [getTemplates(), getGroup(), getUserList()];

  // 仅在新增操作（id 不存在）时调用 getuserinfo
  if (!id) {
    promises.push(getuserinfo());
  }

  // 并行获取模板、分组和用户列表
  await Promise.all(promises);

  if (id) {
    await getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  return baseService.get("/noc/nocly/info/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    return Promise.resolve(); // 返回一个成功的Promise，方便链式调用，用于告知外部该操作已完成
  });
};

//获取当前用户
const getuserinfo = () => {
  return baseService.get("/sys/user/info").then((res) => {
    const remark = res.data.remark;
    const userId = res.data.userId;
    userList.value.push({
      id: userId,
      label:remark,
      value: userId
    });
    dataForm.userIds = [userId];
  });
};



// 自定义过滤方法
const filterMethod = (query: string, option: { label: string; }) => {
  return option.label.toLowerCase().includes(query.toLowerCase());
};


//展会名称列表
const templates = ref<any[]>([]);
const getTemplates = () => {
  baseService.get('/crm/noctemplate/list2', { validStartTimeFlag: 'true', limit: 300 }).then((res) => {
    if (res.code == 0) {
      //刷新
      templates.value = res.data;
    }
  });
};


//分组列表
const groupList = ref<any[]>([]);
const getGroup = () => {
  baseService.post('/noc/noclygroup/list', { limit: 100 }).then((res) => {
    if (res.code == 0) {
      //刷新
      groupList.value = res.data.list;
    }
  });
};


// 展会时间处理函数
const getUrl2 = () => {
  if (!dataForm.id) { // 仅在新增页面时执行
    const selectedTemplate = templates.value.find(t => t.id === dataForm.tid);
    if (selectedTemplate) {
      if (dataForm.ly === 'xianchang') {
        // 当来源为 'xianchang' 时，开始时间为展会的开始时间，结束时间为展会的结束时间
        dataForm.startTime = selectedTemplate.validStartTime;
        dataForm.endTime = selectedTemplate.validEndTime;
      } else if (dataForm.ly === null || dataForm.ly === '') {
        // 当来源未选择时，开始时间为展会的开始时间，结束时间为展会的结束时间
        dataForm.startTime = "";
        dataForm.endTime = selectedTemplate.validStartTime;
      } else {
        // 当来源不为 'xianchang' 时，开始时间为空，结束时间为展会的开始时间
        dataForm.startTime = "";
        dataForm.endTime = selectedTemplate.validStartTime;
      }
    }
  }
};


// 监听 dataForm.ly 的变化
watch(() => dataForm.ly, () => {
  getUrl2();
});

//来源
const getUrl = () => {
  // var port = location.port;
  var hostUrl = "https://preg.jinnoc.com";
  // if (port == '80') {
  //   hostUrl += location.hostname;
  // } else {
  //   hostUrl += location.host;
  // }
  if (!dataForm.ly) {
    dataForm.ly = "";
  }
  if (!dataForm.tid) {
    dataForm.tid = "";
  }
  if (dataForm.ly == 'xianchang') {
    dataForm.url = hostUrl + "/h5/reg?tid=" + dataForm.tid + "&ly=" + dataForm.ly
  } else {
    dataForm.url = hostUrl + "/h5/index?tid=" + dataForm.tid + "&ly=" + dataForm.ly
  }

};

//获取人员
const getUserList = () => {
  return baseService.post("/sys/user/list", {}).then((res) => {
    let list = res.data;
    userList.value = list.map((item: any) => {
      return {
        id: item.userId,
        label: item.remark
      };
    });
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService.post(!dataForm.id ? "/noc/nocly/save" : "/noc/nocly/update", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
}

defineExpose({
  init
});
</script>
<style scoped></style>
